package org.vt.ece3574.pictoslider;

import android.content.Context;
import android.os.SystemClock;
import android.widget.Chronometer;

/**
 * This class represents a timer which can be started and stopped much like a
 * stopwatch.
 * 
 * @author Michael Drescher
 */
public class Timer extends Chronometer {

	/**
	 * True if the timer is running, false if not.
	 */
	private boolean isStarted;

	/**
	 * Keeps track of the amount of time the timer has been running.
	 */
	private long timeRunning;

	/**
	 * @return True if the timer is running, false if not.
	 */
	public boolean isStarted() {
		return isStarted;
	}

	/**
	 * Constructs a new timer with the following parameters.
	 * 
	 * @param base
	 *            - The Timer uses this as its reference (i.e. the time at which
	 *            to display 00:00) when determining what time to display. Base
	 *            is in the form of milliseconds since epoch.
	 * @param context
	 *            - The Timer's context
	 */
	public Timer(long startTime, Context context) {
		super(context);
		timeRunning = startTime;
		super.setBase(SystemClock.elapsedRealtime() + timeRunning);
		isStarted = false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.widget.Chronometer#start()
	 */
	@Override
	public void start() {
		setBase(SystemClock.elapsedRealtime() - timeRunning);
		super.start();
		isStarted = true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.widget.Chronometer#stop()
	 */
	@Override
	public void stop() {
		timeRunning = SystemClock.elapsedRealtime() - getBase();
		super.stop();
		isStarted = false;
	}

	/**
	 * @return The amount of time the timer has been running.
	 */
	public long getTime() {
		if (isStarted())
			timeRunning = SystemClock.elapsedRealtime() - getBase();
		return timeRunning;
	}

}
